#include <openssl/asn1.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
  // Convert integer to ASN1_INTEGER
  ASN1_INTEGER *asn1_int = ASN1_INTEGER_new();
  ASN1_INTEGER_set(asn1_int, 2022);

  // DER encode the integer
  unsigned char *der_bytes = NULL;
  int der_len = i2d_ASN1_INTEGER(asn1_int, &der_bytes);

  // Print the DER-encoded bytes as a hex string
  printf("Integer (DER-encoded):\n");
  for (int i = 0; i < der_len; i++) {
    printf("%02X", der_bytes[i]);
  }
  printf("\n");

  // Base64 encode the DER-encoded bytes
  BIO *bio, *b64;
  BUF_MEM *bufferPtr;

  b64 = BIO_new(BIO_f_base64());
  bio = BIO_new(BIO_s_mem());
  bio = BIO_push(b64, bio);
  BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
  BIO_write(bio, der_bytes, der_len);
  BIO_flush(bio);
  BIO_get_mem_ptr(bio, &bufferPtr);

  // Print the base64-encoded string
  printf("Base64-encoded string:\n");
  printf("%s", bufferPtr->data);

  // Free memory
  ASN1_INTEGER_free(asn1_int);
  OPENSSL_free(der_bytes);
  BIO_free_all(bio);
  
  return 0;
}